package httputil

import (
	"crypto/tls"
	"encoding/json"
	"github.com/go-resty/resty/v2"
	"time"
)

var (
	defaultTimeout          = 5 * time.Second
	defaultRetryWaitTime    = 1 * time.Second
	defaultMaxRetryWaitTime = 5 * time.Second
	defaultMaxRetries       = 3
)

func GetWithClient(client *resty.Client, url string) (int, []byte, error) {
	if client == nil {
		client = GetDefaultClient()
	}
	resp, err := client.R().Get(url)
	if err != nil {
		return 400, []byte{}, err
	}
	body := resp.Body()
	return resp.StatusCode(), body, nil
}

func Get(url string) (int, []byte, error) {
	client := GetDefaultClient()
	return GetWithClient(client, url)
}

func GetWithResult(url string, result interface{}) (int, error) {
	client := GetDefaultClient()
	statusCode, res, err := GetWithClient(client, url)
	if err != nil {
		return 400, err
	}
	if len(res) > 0 && result != nil {
		err = json.Unmarshal(res, result)
		if err != nil {
			return statusCode, err
		}
	}
	return statusCode, nil
}

func GetDefaultClient() *resty.Client {
	client := resty.New().
		SetRetryCount(defaultMaxRetries).
		SetRetryWaitTime(defaultRetryWaitTime).
		SetRetryMaxWaitTime(defaultMaxRetryWaitTime).
		SetTimeout(defaultTimeout).
		SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	return client
}
